import { axios } from "@/plugins/axios"
import merge from "lodash/merge"

class User {
  constructor() {
    this.id = 0
    this.username = ""
    this.userdesc = ""
    this.type = ""
    this.email = ""
    this.active = true
    this.departmentname = ""
    this.update_time = new Date()
    this.create_time = new Date()
  }
  static getCurrentUser() {
    const url = process.env.VUE_APP_API_URL + "api/v1/user/self"
    return axios.get(url).then((res) => {
      let user = new User()
      user = Object.assign(user, res.data.user)
      return user
    })
  }

  get label(){
    return this.userdesc + "-" + this.username + "-" + this.departmentname
  }
}
class SignImage {
  constructor() {
    this.id = ""
    this.image = ""
    this.create_time = ""
    this.user = ""
    this.update_time = ""
  }
}

class UserPubKey {
  constructor() {
    this.id = -1
    this.pubkey = ""
    this.active = true
    this.valid = true
    this.create_time = new Date()
  }
}

// 公司内部的PS用户信息
class PSUser {
  constructor() {
    this.id = ""
    this.loginid = ""
    this.account = ""
    this.sex = ""
    this.department = {}
    this.hs_unit = {}
  }
  static fetch(query_args = {}, page = 1, per_page = 10) {
    const url = process.env.VUE_APP_BJUCD_API_URL + "api/v1/org/user"
    let params = { ...query_args, per_page: per_page, page: page }

    return axios.get(url, { params: params }).then((res) => {
      let results = []
      res.data.results.forEach((item) => {
        const node = merge(new PSUser(), item)
        results.push(node)
      })
      return {
        total: res.data.total,
        pages: res.data.pages,
        results: results,
      }
    })
  }
  static getPSUserInfoByUsername(username) {
    const url = process.env.VUE_APP_BJUCD_API_URL + "api/v1/org/user"
    const query_args = {
      loginid: username,
      extra: true,
    }
    return PSUser.fetch(query_args).then((res) => {
      if (res.total > 0) {
        return res.results[0]
      }else{
        return new PSUser()
      }
    })
  }
}

export default User
export { User, SignImage, UserPubKey, PSUser }
